{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4cd80fa4",
   "metadata": {},
   "source": [
    "# 假设检验基础\n",
    "根据Fisher提出的方法，如果我们想检验关于概率函数p(y)或密度函数f(y)的唯一参数$\\theta$的假设，令$L$表示样本的似然函数，那么为了检验原假设$H_0:\\theta=\\theta_0$，Fisher似然比检验统计量为：\n",
    "$$\n",
    "    \\lambda = \\frac{假定\\theta=\\theta_0时的似然函数}{假定\\theta=\\hat \\theta时的似然函数} = \\frac{L(\\theta_0)}{L(\\hat \\theta)}\n",
    "$$\n",
    "其中$\\hat \\theta$是$\\theta$的极大似然估计。Fisher分析指出，若实际参数值$\\theta$与假设参数值$\\theta_0$不同，那么通过极大似然估计出来的$L(\\hat \\theta)$将远大于$L(\\theta_0)$。这也就说明如果按照如上关系构造检验统计量，该检验统计量的拒绝域<font color=maroon><b>应当由较小的$\\lambda$构成</b></font><br>\n",
    "所幸的是，我们直观选取的检验统计量多数都是相应似然比统计量$\\lambda$的函数，他们同时也都是构造置信区间的枢轴统计量<br>\n",
    "因此，这也就能够说明为什么我们使用假设检验时构造的枢轴统计量与置信区间所使用的枢轴统计量同质"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffd399b7",
   "metadata": {},
   "source": [
    "# 一般假设检验\n",
    "我们常做两个分布的均值检验，在这个范畴下，我们常接触到的假设检验分别是<br>\n",
    "1. 分布方差相同的均值差假设检验\n",
    "2. 分布方差不同的均值差假设检验\n",
    "\n",
    "由于两个不同分布的方差决定不同的假设检验模型，我们在进行假设检验之前需要提前对方差进行估计<br>\n",
    "常见的方差估计模型有<b>Levene</b><font color=red>(没有正态性假设)</font>检验和<b>Bartlett</b><font color=red>(相互独立且正态假设)</font>检验<br>\n",
    "接下来，我们直接对两个分布进行均值差的假设检验"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7dfb256",
   "metadata": {},
   "source": [
    "## 假设检验包\n",
    "1. 方差齐性检验包位于scipy.stats 包下，我们常使用Levene进行检验\n",
    "2. 均值差检验包位于scipy.stats 包下，\n",
    "    > 如果我们在方差齐性检验中得到方差齐性，使用ttest_rel；<br>\n",
    "    > 如果是方差非齐性，使用ttest_ind"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "429a71e3",
   "metadata": {},
   "source": [
    "## sample - 点击转化率\n",
    "### 问题描述\n",
    "某社交APP希望增加直播频道的点击转化率\n",
    "### 实验设计\n",
    "1. 产品方案如下：在直播频道的选项卡上增加红点提示\n",
    "2. 实验设计方法如下：\n",
    "> <b>混淆变量</b>：相同用户行为特征的两组用户，主要控制的变量有 <br>\n",
    "    > 视频的观看习惯：观看时长｜观看互动水平，显示为留言量和弹幕量 <br>\n",
    "    > app的使用习惯：使用app的时间段｜用户生命周期处于同一水平 <br>\n",
    "    > 用户的社会学特征：年龄和地域分层抽样，保证AB两组中用户比例与总体一致 <br>\n",
    "> <b>干预</b>：直播频道选项卡上是否出现红点 <br>\n",
    "> <b>目标变量</b>：直播频道点击转化率 <br>\n",
    "3. 样本量选取\n",
    "4. 实验周期： 5个连续日历天\n",
    "5. 构造假设\n",
    "> $H_0$ = AB两组在直播频道点击转化率上没有本质差异 <br>\n",
    "> $H_1$ = AB两组在直播频道点击转化率上有本质差异\n",
    "6. 检验分布： 由于样本量只有5，因此我们使用t分布进行检验函数的构造"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a690e175",
   "metadata": {},
   "source": [
    "### 数据处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4a30e4ea",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Date</th>\n",
       "      <th>A</th>\n",
       "      <th>B</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2023-09-27</td>\n",
       "      <td>12.796875</td>\n",
       "      <td>12.203125</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2023-09-28</td>\n",
       "      <td>12.703125</td>\n",
       "      <td>10.500000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2023-09-29</td>\n",
       "      <td>12.296875</td>\n",
       "      <td>12.203125</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2023-09-30</td>\n",
       "      <td>13.796875</td>\n",
       "      <td>11.203125</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2023-10-01</td>\n",
       "      <td>11.601562</td>\n",
       "      <td>18.796875</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Date          A          B\n",
       "0 2023-09-27  12.796875  12.203125\n",
       "1 2023-09-28  12.703125  10.500000\n",
       "2 2023-09-29  12.296875  12.203125\n",
       "3 2023-09-30  13.796875  11.203125\n",
       "4 2023-10-01  11.601562  18.796875"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import warnings\n",
    "import os\n",
    "\n",
    "warnings.filterwarnings('ignore')\n",
    "test_res = pd.DataFrame({\"Date\": pd.date_range(start='2023-09-27',end='2023-10-01',freq='D'),\n",
    "                         \"A\":np.array([12.8,12.7,12.3,13.8,11.6],dtype=np.float16),\n",
    "                         \"B\":np.array([12.2,10.5,12.2,11.2,18.8],dtype=np.float16)\n",
    "                        })\n",
    "test_res.head(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c77e01c1",
   "metadata": {},
   "source": [
    "### 方差齐性检验\n",
    "采用Levene方差齐性检验，构造的检验统计量本质上是一个组间方差和组内方差的F检验<br>\n",
    "返回值w即为F检验的实际分布值，p即为显著性变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4d679ef4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "w-value:3.414548215849387\n",
      "p:0.10181205725676695\n"
     ]
    }
   ],
   "source": [
    "from scipy.stats import levene\n",
    "\n",
    "w,p = levene(test_res[\"A\"],test_res[\"B\"],center=\"mean\")\n",
    "print(\"w-value:{}\\np:{}\".format(w,p))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41eb45d8",
   "metadata": {},
   "source": [
    "由于p>$\\alpha=0.05$，我们认为支持原假设，即实验组和对照组方差是相同的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d6d036a3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>A</th>\n",
       "      <th>B</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>count</th>\n",
       "      <td>5.000000</td>\n",
       "      <td>5.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>mean</th>\n",
       "      <td>12.640625</td>\n",
       "      <td>12.976562</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>std</th>\n",
       "      <td>0.800293</td>\n",
       "      <td>3.330078</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>min</th>\n",
       "      <td>11.601562</td>\n",
       "      <td>10.500000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25%</th>\n",
       "      <td>12.296875</td>\n",
       "      <td>11.203125</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>50%</th>\n",
       "      <td>12.703125</td>\n",
       "      <td>12.203125</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>75%</th>\n",
       "      <td>12.796875</td>\n",
       "      <td>12.203125</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>max</th>\n",
       "      <td>13.796875</td>\n",
       "      <td>18.796875</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "               A          B\n",
       "count   5.000000   5.000000\n",
       "mean   12.640625  12.976562\n",
       "std     0.800293   3.330078\n",
       "min    11.601562  10.500000\n",
       "25%    12.296875  11.203125\n",
       "50%    12.703125  12.203125\n",
       "75%    12.796875  12.203125\n",
       "max    13.796875  18.796875"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_res.describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4adc4157",
   "metadata": {},
   "source": [
    "### 假设检验"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "62393ddd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t-value:-0.22446175163718796\n",
      "p:0.8280247967287839\n"
     ]
    }
   ],
   "source": [
    "from scipy.stats import ttest_ind, ttest_rel\n",
    "\n",
    "t,p = ttest_ind(test_res[\"A\"],test_res[\"B\"],equal_var=True)\n",
    "print(\"t-value:{}\\np:{}\".format(t,p))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e93838a",
   "metadata": {},
   "source": [
    "### 结果分析\n",
    "结果表明，p值远大于$\\alpha=0.05$，我们没有充分的理由拒绝原假设$H_0$，也就是说明AB两个实验不存在显著差异，<br>因此我们可以得出结论，该产品的优化没有达到预期<br>我们不能认为红点方案对于提升直播频道点击转化率有促进作用"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1a5f356",
   "metadata": {},
   "source": [
    "# 检验两个均值的差：配对\n",
    "对同一组实验对象，控制混淆变量后，我们只改变目标变量，此时将会得到两个实验统计总体<br>\n",
    "由于两个实验总体是相关的，因此我们做假设检验的总体思想是将两个总体样本间的差值作为假设检验统计量"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e46ba8a9",
   "metadata": {},
   "source": [
    "## 大样本检验\n",
    "当样本容量$n>30$时，我们可以采用Z检验\n",
    "### 单侧检验\n",
    "$$\n",
    "    H_0: (\\mu_1-\\mu_2) = D_0 \\\\\n",
    "    H_1: (\\mu_1-\\mu_2) > D_0 ;\\\\ \n",
    "    [H_1: (\\mu_1-\\mu_2) < D_0]\n",
    "$$\n",
    "检验统计量：\n",
    "$$\n",
    "    Z = \\frac{\\bar d - D_0}{\\sigma_d/\\sqrt{n}} \\approx \\frac{\\bar d - D_0}{s_d/\\sqrt{n}}\n",
    "$$\n",
    "其中$\\bar d$和$s_d$分别表示样本的均值和标准差<br>\n",
    "拒绝域：\n",
    "$$\n",
    "     Z > z_\\alpha ; \\\\\n",
    "     [Z < -z_\\alpha]\\\\\n",
    "     p = P\\{Z>z_c\\} < \\alpha;\\\\\n",
    "     [p = P\\{Z<z_c\\} < \\alpha]\n",
    "$$\n",
    "其中，$z_c$是检验统计量的计算值"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c144bd3",
   "metadata": {},
   "source": [
    "### 双侧检验\n",
    "原假设与备择假设：\n",
    "$$\n",
    "    H_0: (\\mu_1-\\mu_2) = D_0 \\\\\n",
    "    H_1: (\\mu_1-\\mu_2) \\ne D_0\n",
    "$$\n",
    "检验统计量：\n",
    "$$\n",
    "    Z = \\frac{\\bar d - D_0}{\\sigma_d/\\sqrt{n}} \\approx \\frac{\\bar d - D_0}{s_d/\\sqrt{n}}\n",
    "$$\n",
    "其中$\\bar d$和$s_d$分别表示样本的均值和标准差<br>\n",
    "拒绝域：\n",
    "$$\n",
    "     Z > |z_{\\alpha/2}| \\\\\n",
    "     p = 2P\\{Z>z_c\\} < \\alpha\n",
    "$$\n",
    "其中，$z_c$是检验统计量的计算值<br>\n",
    "注意，双侧检验的显著性变量p应为单侧检验的2倍，因为我们要关注的“小概率事件”实际上是Z正太分布的上尾和下尾"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17698ab5",
   "metadata": {},
   "source": [
    "## 小样本检验\n",
    "由于实际情况中我们很少能够对数据进行大样本的假设，因此我们一般使用对尾分布更加平滑的t分布\n",
    "### 单侧检验\n",
    "原假设与备择假设：\n",
    "$$\n",
    "    H_0: (\\mu_1-\\mu_2) = D_0 \\\\\n",
    "    H_1: (\\mu_1-\\mu_2) > D_0;\\\\ \n",
    "    [H_1: (\\mu_1-\\mu_2) < D_0]\n",
    "$$\n",
    "检验统计量：\n",
    "$$\n",
    "    T = \\frac{\\bar d - D_0}{\\sigma_d/\\sqrt{n}} \\approx \\frac{\\bar d - D_0}{s_d/\\sqrt{n}}\n",
    "$$\n",
    "其中$\\bar d$和$s_d$分别表示样本的均值和标准差<br>\n",
    "拒绝域：\n",
    "$$\n",
    "     T > t_\\alpha ; \\\\\n",
    "     [T < -t_\\alpha]\\\\\n",
    "     p = P\\{T>t_c\\} < \\alpha;\\\\\n",
    "     [p = P\\{T<t_c\\} < \\alpha]\n",
    "$$\n",
    "其中，$t_c$是检验统计量的计算值"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c38e5dc5",
   "metadata": {},
   "source": [
    "### 双侧检验\n",
    "原假设与备择假设：\n",
    "$$\n",
    "    H_0: (\\mu_1-\\mu_2) = D_0 \\\\\n",
    "    H_1: (\\mu_1-\\mu_2) \\ne D_0\n",
    "$$\n",
    "检验统计量：\n",
    "$$\n",
    "    T = \\frac{\\bar d - D_0}{\\sigma_d/\\sqrt{n}} \\approx \\frac{\\bar d - D_0}{s_d/\\sqrt{n}}\n",
    "$$\n",
    "其中$\\bar d$和$s_d$分别表示样本的均值和标准差<br>\n",
    "拒绝域：\n",
    "$$\n",
    "     T > |t_{\\alpha/2}| \\\\\n",
    "     p = 2P\\{T>t_c\\} < \\alpha\n",
    "$$\n",
    "其中，$t_c$是检验统计量的计算值<br>\n",
    "注意，双侧检验的显著性变量p应为单侧检验的2倍，因为我们要关注的“小概率事件”实际上是T分布的上尾和下尾"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67814722",
   "metadata": {},
   "source": [
    "## t检验实例\n",
    "### 假设检验包\n",
    "scipy.stats 包中提供多种假设检验的工具<br>\n",
    "对于假设检验来说，最为重要的计算机优化点实际上在于样本均值和方差的计算，<br>\n",
    "与此同时，计算机还需要根据自由度存储相应统计分布的分位值数据，除此之外我们完全可以手动完成如上计算工作\n",
    "### sample - 人工降雨\n",
    "人工降雨：考虑人工降雨试验，比较5个耕作地区的使用催化求雨技术与否的月降水量，<br>\n",
    "在这个实验中，目标变量时对该地区使用催化，观察对象是5个耕作地区"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1480d9a6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>catalyzed</th>\n",
       "      <th>uncatalyzed</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1.75</td>\n",
       "      <td>1.62</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2.12</td>\n",
       "      <td>1.83</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1.53</td>\n",
       "      <td>1.40</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1.10</td>\n",
       "      <td>0.75</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>1.70</td>\n",
       "      <td>1.71</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   catalyzed  uncatalyzed\n",
       "1       1.75         1.62\n",
       "2       2.12         1.83\n",
       "3       1.53         1.40\n",
       "4       1.10         0.75\n",
       "5       1.70         1.71"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np \n",
    "import pandas as pd\n",
    "import warnings \n",
    "from scipy.stats import ttest_1samp\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "decipitation = np.array([[1.75,2.12,1.53,1.10,1.70],\n",
    "                         [1.62,1.83,1.40,0.75,1.71]])\n",
    "df_decipitation = pd.DataFrame(columns=np.arange(1,6,1),\n",
    "                               index=[\"catalyzed\",\"uncatalyzed\"],\n",
    "                               data=decipitation).transpose()\n",
    "df_decipitation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "08e312c3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>catalyzed</th>\n",
       "      <th>uncatalyzed</th>\n",
       "      <th>d</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1.75</td>\n",
       "      <td>1.62</td>\n",
       "      <td>0.13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2.12</td>\n",
       "      <td>1.83</td>\n",
       "      <td>0.29</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1.53</td>\n",
       "      <td>1.40</td>\n",
       "      <td>0.13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1.10</td>\n",
       "      <td>0.75</td>\n",
       "      <td>0.35</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>1.70</td>\n",
       "      <td>1.71</td>\n",
       "      <td>-0.01</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   catalyzed  uncatalyzed     d\n",
       "1       1.75         1.62  0.13\n",
       "2       2.12         1.83  0.29\n",
       "3       1.53         1.40  0.13\n",
       "4       1.10         0.75  0.35\n",
       "5       1.70         1.71 -0.01"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_decipitation[\"d\"] = df_decipitation.catalyzed - df_decipitation.uncatalyzed\n",
    "df_decipitation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "21a0be80",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t=2.778537907692358,\n",
      "p=0.04989306151921203\n"
     ]
    }
   ],
   "source": [
    "t,p = ttest_1samp(df_decipitation.d,0)\n",
    "print(\"t={},\\np={}\".format(t,p))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8fb2b3bf",
   "metadata": {},
   "source": [
    "由于scipy.stats尝试做双边t检验，因此得出的p结果如果应用到单侧，应当做对半处理，<br>\n",
    "同时我们发现t值处于t分布右半曲线，因此原假设的确应当是右侧(即>)单边检验<br>\n",
    "由于我们在假设时将催化分布样本减去为催化分布样本，因此我们的原假设和备择假设实际上是：\n",
    "$$\n",
    "    H_0: (\\mu_1-\\mu_2) = 0 \\\\\n",
    "    H_1: (\\mu_1-\\mu_2) > 0\n",
    "$$\n",
    "即当我们得到单侧检验p值为0.025左右时，可以拒绝原假设而得出<font color=maroon><b>催化地区平均月降水量大于未催化地区</b></font>的结论"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfd8adfd",
   "metadata": {},
   "source": [
    "# 检验两个比值的差\n",
    "由于二项分布当满足$npq \\ge 4$的条件时能够被近似视为服从$N~(np,npq)$的正态分布，<br>\n",
    "因此我们也能够通过大样本比率构造假设检验的枢轴统计量Z；<br>\n",
    "不同于两个样本之间均值的比较，两个样本比率的比较更关心的是某个实验结果出现比率之间的比较"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d18475e",
   "metadata": {},
   "source": [
    "## 单侧检验\n",
    "原假设和备择假设：\n",
    "$$\n",
    "    H_0: (p_1 - p_2) = D_0 \\\\\n",
    "    H_1: (p_1 - p_2) > D_0; \\\\\n",
    "    [H_1: (p_1 - p_2 ) < D_0] \n",
    "$$\n",
    "检验统计量：\n",
    "$$\n",
    "    T  =  \\frac{(\\hat p_1 - \\hat p_2) - D_0}{\\sigma_{(\\hat p_1 - \\hat p_2)}} \n",
    "$$\n",
    "\n",
    "$$\n",
    "\\left \\{\n",
    "\\begin{array}{ll}\n",
    "    \\sigma_{(\\hat p_1 - \\hat p_2)} & = & \\sqrt{\\frac{\\hat p_1 \\hat q_1}{n_1}+\\frac{\\hat p_2 \\hat q_2}{n_2}}, D_0 \\ne 0 \\\\\n",
    "    \\sigma_{(\\hat p_1 - \\hat p_2)} & = & \\sqrt{\\hat p \\hat q(\\frac{1}{n_1}+\\frac{1}{n_2})}, D_0 = 0 \\\\\n",
    "    \\hat p & = & \\frac{y_1 + y_2}{n_1+n_2} \\\\\n",
    "\\end{array}\n",
    "\\right .\n",
    "$$\n",
    "其中$\\hat p_1$和$\\hat p_2$分别表示两个分布期望发生事件的比率，而$\\hat q_1 = 1- \\hat p_1$,$\\hat q_2 = 1- \\hat p_2$<br>\n",
    "当$D_0 = 0$时，$y_1,y_2$分别是两个总体中关注事件的发生频次，$n_1,n_2$是两个总体的样本容量<br>\n",
    "拒绝域：\n",
    "$$\n",
    "     Z > z_\\alpha ; \\\\\n",
    "     [Z < -z_\\alpha]\\\\\n",
    "     p = P\\{Z>z_c\\} < \\alpha;\\\\\n",
    "     [p = P\\{Z<z_c\\} < \\alpha]\n",
    "$$\n",
    "其中，$z_c$是检验统计量的计算值"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f4a5244",
   "metadata": {},
   "source": [
    "## 双侧检验\n",
    "原假设和备择假设：\n",
    "$$\n",
    "    H_0: (p_1 - p_2) = D_0 \\\\\n",
    "    H_1: (p_1 - p_2) \\ne D_0\n",
    "$$\n",
    "检验统计量：\n",
    "$$\n",
    "    T  =  \\frac{(\\hat p_1 - \\hat p_2) - D_0}{\\sigma_{(\\hat p_1 - \\hat p_2)}} \n",
    "$$\n",
    "\n",
    "$$\n",
    "\\left \\{\n",
    "\\begin{array}{ll}\n",
    "    \\sigma_{(\\hat p_1 - \\hat p_2)} & = & \\sqrt{\\frac{\\hat p_1 \\hat q_1}{n_1}+\\frac{\\hat p_2 \\hat q_2}{n_2}}, D_0 \\ne 0 \\\\\n",
    "    \\sigma_{(\\hat p_1 - \\hat p_2)} & = & \\sqrt{\\hat p \\hat q(\\frac{1}{n_1}+\\frac{1}{n_2})}, D_0 = 0 \\\\\n",
    "    \\hat p & = & \\frac{y_1 + y_2}{n_1+n_2} \\\\\n",
    "\\end{array}\n",
    "\\right .\n",
    "$$\n",
    "其中$\\hat p_1$和$\\hat p_2$分别表示两个分布期望发生事件的比率，而$\\hat q_1 = 1- \\hat p_1$,$\\hat q_2 = 1- \\hat p_2$<br>\n",
    "当$D_0 = 0$时，$y_1,y_2$分别是两个总体中关注事件的发生频次，$n_1,n_2$是两个总体的样本容量<br>\n",
    "拒绝域：\n",
    "$$\n",
    "     Z > z_\\alpha/2 \\\\\n",
    "     p = 2P\\{Z>｜z_c｜\\} < \\alpha\n",
    "$$\n",
    "其中，$z_c$是检验统计量的计算值"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf020db6",
   "metadata": {},
   "source": [
    "## 比率检验实例\n",
    "由于比率检验较为简单，我们可以通过手动的方式进行计算\n",
    "### sample - 拼车研究\n",
    "进来正兴起一场运动，鼓励人们合伙拼车上班以节约能源，计划是指定某些高速公路只能由拼车使用<br>\n",
    "某一城市的收费站工作人员分别在拼车专用公路上与计划实施前后随机选取了2000辆和1500辆汽车，<br>\n",
    "调查结果为：<br>\n",
    "建立拼车道前 $n_1=2000$, 拼车数$y_1=652$<br>\n",
    "建立拼车道后 $n_1=1500$, 拼车数$y_1=576$<br>\n",
    "试问这些数据能否证明计划实施后合乘汽车比率有所提高？$\\alpha=0.05$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a3bb6d1f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "p:0.35085714285714287,\n",
      "sigma:0.016300791683958468, \n",
      "Zc:-3.558109392752839\n",
      "Z:-1.6448536269514722\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import warnings \n",
    "import math\n",
    "from scipy.stats import norm\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "p1 = 652/2000\n",
    "p2 = 576/1500\n",
    "p = (652+576)/(2000+1500)\n",
    "q = 1-p\n",
    "sigma = math.sqrt(p*q*(1/2000+1/1500))\n",
    "Z = (p1-p2-0)/sigma\n",
    "\n",
    "print(\"p:{},\\nsigma:{}, \\nZc:{}\".format(p,sigma,Z))\n",
    "\n",
    "alpha = 0.05\n",
    "z = -norm.ppf(1-alpha)\n",
    "print(\"Z:{}\".format(z))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e37e246",
   "metadata": {},
   "source": [
    "由于我们一开始做单边检验，\n",
    "$$ \n",
    "    H_0: (p_1 - p_2) = D_0 \\\\\n",
    "    H_1: (p_1 - p_2 ) < D_0   \n",
    "$$ \n",
    "故当$Z_c<z_\\alpha$时我们选择拒绝原假设，认定采取措施后拼车率的确有所提高"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d6d172d",
   "metadata": {},
   "source": [
    "# 检验多个比值的差 - 单向表检验\n",
    "## 概念\n",
    "当我们关注的事件不再是01事件而是分立的几个时，每一个事件都会拥有一个比率，<br>\n",
    "此时我们希望每一个事件发生的比率是某一组数值，这也就是我们进行单向表检验的原假设<br>\n",
    "在这个假设检验中，我们将要借助卡方分布<br>\n",
    "卡方分布这一枢轴统计量的构造数学逻辑也十分清晰，<br>\n",
    "我们只需要保证<font color=maroon><b>观测和期望比率的离差加权平方和最小</b></font>即可，该统计量的构造也是完全符合Fisher假设的\n",
    "\n",
    "## 卡方检验 \n",
    "假定：<br>\n",
    "为了卡方近似的有效性，对所有$n_i$都有$E(n_i)\\ge 5$<br>\n",
    "\n",
    "原假设和备择假设\n",
    "$$\n",
    "\\begin{array}{ll}\n",
    "    H_0: p_1= p_{1,0},p_2= p_{2,0},\\cdots,p_k= p_{k,0} \\\\\n",
    "    H_1: 至少有一个多项概率不等于假设值\n",
    "\\end{array}\n",
    "$$\n",
    "其中，$p_{k,0}$代表多项概率的假设值<br>\n",
    "检验统计量：\n",
    "$$\n",
    "    \\chi_c^2 = \\sum_{i=1}^k \\frac{{[n_i -E(n_i)]}^2}{E(n_i)} = (\\sum_{i=1}^k \\frac{{n_i}^2}{np_i})-n\n",
    "$$\n",
    "其中，$E(n_i)=np_{i,0}$是在$H_0$成立的条件下得到类型i的期望个数，总样本大小为n<br>\n",
    "拒绝域：\n",
    "$$\n",
    "    \\chi_c^2 > \\chi_\\alpha^2 \\\\\n",
    "    p=P\\{\\chi^2>\\chi_c^2\\}\n",
    "$$\n",
    "注意，这里$\\chi_\\alpha^2$有$(k-1)$个自由度"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e12f4220",
   "metadata": {},
   "source": [
    "## 单向表检验实例\n",
    "### sample - 车间不合格样品比率\n",
    "一共有$n=103$个不合格样品，分别来自5条生产线，<br>\n",
    "下面需要检验5条生产线生产出的不合格样品比率是否相等<br>\n",
    "生产线1:15<br>\n",
    "生产线2:27<br>\n",
    "生产线3:31<br>\n",
    "生产线4:19<br>\n",
    "生产线5:11<br>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "34117a87",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mean:20.6\n",
      "chi2_c:13.359223300970873\n",
      "9.487729036781154\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import math\n",
    "import warnings\n",
    "from scipy.stats import chi2\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "alpha = 0.05\n",
    "n = 5\n",
    "mean = (15+27+31+19+11)/5\n",
    "chi2_c= (math.pow((15-mean),2)+math.pow((27-mean),2) \\\n",
    "        +math.pow((31-mean),2)+math.pow((19-mean),2) \\\n",
    "        +math.pow((11-mean),2))/mean\n",
    "\n",
    "chi2_a = chi2(n-1).ppf(1-alpha)\n",
    "\n",
    "print(\"mean:{}\\nchi2_c:{}\".format(mean,chi2_c))\n",
    "print(chi2_a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "00af1fc0",
   "metadata": {},
   "source": [
    "由于我们的原假设是每一个比率都是相同的，即\n",
    "$$\n",
    "\\begin{array}{ll}\n",
    "    H_0: p_1= 0.2,p_2= 0.2,\\cdots,p_5= 0.2 \\\\\n",
    "    H_1: 至少有一个多项概率不等于假设值\n",
    "\\end{array}\n",
    "$$\n",
    "结果通过计算我们发觉$ \\chi_c^2 > \\chi_\\alpha^2$，因此我们选择拒绝原假设<br>\n",
    "即<font color=maroon><b>至少有一条生产线比其他生产线对较高的不合格率富有责任</b></font>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64b72c4d",
   "metadata": {},
   "source": [
    "# 检验类型的两个方向是否相关 - 列联表检验"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4919dd32",
   "metadata": {},
   "outputs": [],
   "source": [
    " "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3.6",
   "language": "python",
   "name": "python3.6"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "301.398px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
